<template>
  <div id="app" class="min-h-screen transition-colors duration-300"
       :class="[themeStore.theme.bg.primary, themeStore.theme.text.primary]">
    <!-- 主界面 -->
    <div class="flex min-h-screen">
      <!-- 顶部导航栏 - 融合版 -->
      <div class="fixed top-0 left-0 right-0 z-50 border-b transition-colors duration-300"
           :class="[themeStore.theme.bg.secondary, themeStore.theme.border.primary]">
        <div class="flex items-center justify-between px-4 py-3">
          <!-- 左侧区域：折叠按钮 + Logo + 聊天信息 -->
          <div class="flex items-center space-x-3">
            <!-- 侧边栏折叠按钮 - 桌面端 -->
            <button 
              @click="toggleSidebar"
              class="p-1.5 text-gray-400 hover:text-white transition-colors hidden md:block"
              title="折叠侧边栏"
            >
              <font-awesome-icon :icon="sidebarCollapsed ? 'chevron-right' : 'chevron-left'" class="text-sm" />
            </button>
            
            <!-- Logo和应用标题 -->
            <div class="flex items-center space-x-2">
              <div class="w-6 h-6 bg-gradient-to-r from-blue-500 to-purple-600 rounded flex items-center justify-center">
                <font-awesome-icon icon="brain" class="text-white text-sm" />
              </div>
              <h1 class="text-lg font-semibold text-white">心理咨询机器人</h1>
            </div>
            
            <!-- 分隔线 -->
            <div class="h-6 w-px bg-gray-600 hidden md:block"></div>
            
            <!-- 当前聊天信息 -->
            <div class="flex items-center space-x-2 hidden md:flex">
              <div class="w-5 h-5 bg-indigo-600 rounded-full flex items-center justify-center">
                <font-awesome-icon icon="robot" class="text-white text-xs" />
              </div>
              <div>
                <h2 class="text-sm font-medium text-white">
                  {{ getCurrentConversationTitle() }}
                </h2>
                <p class="text-xs text-gray-400">
                  {{ isLoading ? '正在输入...' : '在线 · 随时为您提供帮助' }}
                </p>
              </div>
            </div>
          </div>
          
          <!-- 右侧区域：聊天操作 + 用户操作 -->
          <div class="flex items-center space-x-2">
            <!-- 聊天操作按钮 -->
            <div class="flex items-center space-x-1 mr-2">
              <button
                @click="clearCurrentChat"
                class="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors duration-200"
                title="清空对话"
              >
                <font-awesome-icon icon="broom" class="h-3 w-3" />
              </button>
              <button
                @click="exportCurrentChat"
                class="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors duration-200"
                title="导出对话"
              >
                <font-awesome-icon icon="download" class="h-3 w-3" />
              </button>
            </div>
            
            <!-- 移动端菜单按钮 -->
            <button 
              @click="showMobileSidebar = true"
              class="p-1.5 text-gray-400 hover:text-white transition-colors md:hidden"
              title="菜单"
            >
              <font-awesome-icon icon="bars" class="text-sm" />
            </button>
            
            <!-- 用户区域 -->
            <div v-if="isLoggedIn" class="flex items-center space-x-1">
              <span class="text-gray-300 text-sm hidden sm:block">{{ userInfo?.username || userInfo?.email }}</span>
              <button
                @click="showProfile = true"
                class="p-1.5 transition-colors"
                :class="[themeStore.theme.text.tertiary, 'hover:' + themeStore.theme.text.primary]"
                title="用户资料"
              >
                <font-awesome-icon icon="user" class="text-sm" />
              </button>
              <button
                @click="showSettings = true"
                class="p-1.5 transition-colors"
                :class="[themeStore.theme.text.tertiary, 'hover:' + themeStore.theme.text.primary]"
                title="设置"
              >
                <font-awesome-icon icon="cog" class="text-sm" />
              </button>

              <!-- 主题切换按钮 -->
              <div class="ml-2">
                <ThemeToggle />
              </div>
              <button 
                @click="handleLogout"
                class="p-1.5 text-gray-400 hover:text-white transition-colors"
                title="退出登录"
              >
                <font-awesome-icon icon="sign-out-alt" class="text-sm" />
              </button>
            </div>
            <div v-else class="flex items-center space-x-3">
              <button
                @click="showLogin = true"
                class="px-3 py-1.5 rounded text-sm transition-colors"
                :class="themeStore.theme.button.primary"
              >
                登录
              </button>

              <!-- 主题切换按钮 -->
              <ThemeToggle />
            </div>
          </div>
        </div>
      </div>
      
      <!-- 主内容区域 - 紧凑版 -->
      <div class="flex w-full pt-16">
        <!-- 侧边栏 - 响应式，参考GPT官网比例，固定定位 -->
        <div 
          class="fixed left-0 top-16 bottom-0 z-30 flex-shrink-0 hidden md:block transition-all duration-300 ease-in-out bg-gray-800"
          :class="sidebarCollapsed ? 'w-0' : 'w-60'"
        >
          <div 
            class="h-full overflow-hidden transition-all duration-300 ease-in-out"
            :class="sidebarCollapsed ? 'w-0 opacity-0' : 'w-60 opacity-100'"
          >
            <Sidebar 
              :conversations="conversations"
              :current-conversation-id="currentConversationId"
              :is-logged-in="isLoggedIn"
              :is-collapsed="sidebarCollapsed"
              @new-conversation="createNewConversation"
              @select-conversation="selectConversation"
              @delete-conversation="deleteConversation"
              @title-updated="handleTitleUpdated"
            />
          </div>
        </div>
        
        <!-- 移动端侧边栏 -->
        <div v-if="showMobileSidebar" class="fixed inset-0 z-50 md:hidden">
          <div class="fixed inset-0 bg-black bg-opacity-50" @click="showMobileSidebar = false"></div>
          <div class="fixed left-0 top-0 bottom-0 w-60 bg-gray-900 pt-16">
            <Sidebar 
              :conversations="conversations"
              :current-conversation-id="currentConversationId"
              :is-logged-in="isLoggedIn"
              @new-conversation="createNewConversation"
              @select-conversation="selectConversation"
              @delete-conversation="deleteConversation"
              @title-updated="handleTitleUpdated"
            />
          </div>
        </div>
        
        <!-- 聊天区域 - 响应式，适应固定侧边栏 -->
        <div 
          class="flex-1 w-full md:w-auto transition-all duration-300 ease-in-out"
          :class="sidebarCollapsed ? 'md:ml-0' : 'md:ml-60'"
        >
          <ChatArea
            ref="chatAreaRef"
            :conversation-id="currentConversationId"
            :messages="currentMessages"
            :is-loading="isLoading"
            :is-currently-thinking="isCurrentlyThinking"
            :is-logged-in="isLoggedIn"
            :sidebar-collapsed="sidebarCollapsed"
            @send-message="sendMessage"
            @clear-chat="clearCurrentChat"
            @export-chat="exportCurrentChat"
            @feedback-updated="handleFeedbackUpdated"
          />
        </div>
      </div>
    </div>

    <!-- 用户引导组件 -->
    <UserGuide
      ref="userGuideRef"
      @guide-completed="handleGuideCompleted"
      @guide-skipped="handleGuideSkipped"
    />

    <!-- 快速开始建议 -->
    <QuickStartSuggestions
      ref="quickStartRef"
      @suggestion-selected="handleSuggestionSelected"
      @direct-chat-started="handleDirectChatStarted"
      @suggestions-hidden="handleSuggestionsHidden"
    />

    <!-- 登录模态框 - 响应式紧凑版 -->
     <div v-if="showLogin" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-2">
       <div class="bg-gray-800 rounded-lg p-2 w-full max-w-xs mx-auto max-h-[80vh] overflow-y-auto">
         <div class="flex justify-between items-center mb-1">
           <h2 class="text-base font-semibold text-white">登录</h2>
           <button @click="showLogin = false" class="text-gray-400 hover:text-white transition-colors">
             <font-awesome-icon icon="times" class="w-3 h-3" />
           </button>
         </div>
         <LoginComponent :isModal="true" @login-success="handleLoginSuccess" />
       </div>
     </div>
    
    <!-- 用户资料模态框 -->
    <UserProfile v-if="showProfile" :user-info="userInfo" @close="showProfile = false" />
    
    <!-- 设置模态框 - 响应式 -->
    <div v-if="showSettings" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-2">
      <div class="bg-gray-800 rounded-lg p-3 w-full max-w-xs mx-auto max-h-[80vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-2">
          <h2 class="text-lg font-semibold text-white">设置</h2>
          <button @click="showSettings = false" class="text-gray-400 hover:text-white transition-colors">
            <font-awesome-icon icon="times" class="w-4 h-4" />
          </button>
        </div>
        <Settings @close="showSettings = false" />
      </div>
    </div>


  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
import api from './api/index.js'
import { useUserStore } from './stores/user'
import { useThemeStore } from './stores/theme'
import LoginComponent from './components/LoginComponent.vue'
import Sidebar from './components/Sidebar.vue'
import ChatArea from './components/ChatArea.vue'
import ThemeToggle from './components/ThemeToggle.vue'
import UserProfile from './components/UserProfile.vue'
import Settings from './components/Settings.vue'
import UserGuide from './components/UserGuide.vue'
import QuickStartSuggestions from './components/QuickStartSuggestions.vue'

export default {
  name: 'App',
  components: {
    LoginComponent,
    Sidebar,
    ChatArea,
    UserProfile,
    Settings,
    ThemeToggle,
    UserGuide,
    QuickStartSuggestions
  },
  setup() {
    // 使用 Pinia 状态管理
    const userStore = useUserStore()
    const themeStore = useThemeStore()

    // Computed 属性（需要在函数定义之前）
    const isLoggedIn = computed(() => userStore.isAuthenticated)
    const userInfo = computed(() => userStore.userInfo)

    // 响应式数据
    const conversations = ref([])
    const currentConversationId = ref(null)
    const currentMessages = ref([])
    const isLoading = ref(false)
    const showProfile = ref(false)
    const showSettings = ref(false)
    const showLogin = ref(false)
    const showMobileSidebar = ref(false)
    const sidebarCollapsed = ref(false)
    const chatAreaRef = ref(null) // ChatArea组件引用
    const userGuideRef = ref(null) // 用户引导组件引用
    const quickStartRef = ref(null) // 快速开始建议组件引用

    // 思考过程相关数据
    const currentThinkingSteps = ref([])
    const currentThinkingContent = ref('')
    const isCurrentlyThinking = ref(false)
    
    // 检查登录状态（使用 Pinia）
    const checkLoginStatus = async () => {
      console.log('🔍 [App] 使用Pinia检查登录状态...')

      // 使用 Pinia 验证并恢复登录状态
      const isRestored = await userStore.validateAndRestoreAuth()

      if (isRestored) {
        console.log('✅ [App] 登录状态已恢复，加载对话列表')
        await loadConversations()
      } else {
        console.log('⚠️ [App] 没有有效的登录状态')
      }
    }

    // 处理登录成功（使用 Pinia）
    const handleLoginSuccess = async (userData) => {
      console.log('✅ [App] 登录成功，更新用户状态')

      // 使用 Pinia 更新用户信息
      userStore.updateUserInfo(userData)

      // 关闭登录模态框
      showLogin.value = false

      // 加载对话列表
      await loadConversations()

      console.log('🎉 [App] 登录流程完成')
    }

    // 处理退出登录（使用 Pinia）
    const handleLogout = () => {
      console.log('🚪 [App] 用户退出登录')

      // 使用 Pinia 清除用户状态
      userStore.logout()

      // 清除应用状态
      conversations.value = []
      currentConversationId.value = null
      currentMessages.value = []

      console.log('🧹 [App] 应用状态已清除')
    }

    // 加载对话列表
    const loadConversations = async () => {
      const response = await api.getConversations()
      if (response.success) {
        // 按时间倒序排列（最新的在上面）
        const sortedConversations = response.data.sort((a, b) => {
          const dateA = new Date(a.created_at || a.updated_at)
          const dateB = new Date(b.created_at || b.updated_at)
          return dateB - dateA // 倒序排列
        })

        conversations.value = sortedConversations
        console.log('📋 [Conversations] 对话列表已按时间排序:', sortedConversations.length, '条对话')

        if (sortedConversations.length > 0) {
          // 选择最新的对话（排序后的第一个）
          currentConversationId.value = sortedConversations[0].conversation_id
          await loadMessages(sortedConversations[0].conversation_id)
        }
      } else {
        throw new Error(`加载对话列表失败: ${response.message || '未知错误'}`)
      }
    }

    // 加载消息
    const loadMessages = async (conversationId) => {
      // 如果是临时ID，不需要加载消息
      if (conversationId?.startsWith('temp_')) {
        currentMessages.value = []
        return
      }

      isLoading.value = true

      // 直接调用API，不捕获异常，让错误直接暴露
      const response = await api.getMessages(conversationId)

      if (response.success) {
        // 处理消息数据，包括思考过程
        currentMessages.value = response.data.map(message => {
          console.log('🔍 [LoadMessages] 处理消息:', message.message_id, '思考过程:', !!message.thinking_process)

          // 如果是assistant消息且有思考过程，创建思考过程消息
          if (message.role === 'assistant' && message.thinking_process) {
            console.log('✅ [LoadMessages] 发现思考过程数据:', {
              total_iterations: message.thinking_process.total_iterations,
              content_length: message.thinking_process.total_thinking_content?.length || 0,
              iterations_count: message.thinking_process.iterations?.length || 0
            })

            const processedMessages = []

            // 先添加思考过程消息
            const thinkingMsg = {
              id: message.id + '_thinking',
              role: 'system',
              type: 'thinking_block',
              timestamp: message.created_at,
              isThinking: false, // 已完成的思考
              thinkingSteps: [],
              detailedContent: message.thinking_process.total_thinking_content || '',
              allThinkingContent: message.thinking_process.total_thinking_content || '',
              thinkingIterations: message.thinking_process.iterations || []
            }
            processedMessages.push(thinkingMsg)

            // 再添加AI回复消息
            processedMessages.push({
              id: message.id,
              message_id: message.message_id,
              role: message.role,
              content: message.content,
              displayText: message.content,
              timestamp: message.created_at,
              type: 'content',
              feedback: message.feedback
            })

            return processedMessages
          } else {
            // 普通消息
            return [{
              id: message.id,
              message_id: message.message_id,
              role: message.role,
              content: message.content,
              displayText: message.content,
              timestamp: message.created_at,
              type: message.role === 'user' ? 'user' : 'content',
              feedback: message.feedback
            }]
          }
        }).flat() // 展平数组

        console.log('✅ [LoadMessages] 消息处理完成，总消息数:', currentMessages.value.length)

        // 🔥 Vue3最佳实践：加载消息后自动滚动到底部
        await nextTick()
        if (chatAreaRef.value) {
          await chatAreaRef.value.scrollToBottom()
        }
      } else {
        // API返回失败，抛出错误
        throw new Error(`API返回失败: ${response.message || '未知错误'}`)
      }

      isLoading.value = false
    }

    // 创建新对话
    const createNewConversation = async () => {
      try {
        const response = await api.createConversation()
        if (response.success) {
          conversations.value.unshift(response.data)
          currentConversationId.value = response.data.conversation_id
          currentMessages.value = []
        }
      } catch (error) {
        console.error('创建新对话失败:', error)
      }
    }

    // 选择对话
    const selectConversation = async (conversationId) => {
      currentConversationId.value = conversationId
      await loadMessages(conversationId)
    }

    // 删除对话
    const deleteConversation = async (conversationId) => {
      try {
        const response = await api.deleteConversation(conversationId)
        if (response.success) {
          conversations.value = conversations.value.filter(c => c.conversation_id !== conversationId)
          if (currentConversationId.value === conversationId) {
            if (conversations.value.length > 0) {
              currentConversationId.value = conversations.value[0].conversation_id
              await loadMessages(conversations.value[0].conversation_id)
            } else {
              currentConversationId.value = null
              currentMessages.value = []
            }
          }
        }
      } catch (error) {
        console.error('删除对话失败:', error)
      }
    }

    // 发送消息
    const sendMessage = async (content) => {
      // 如果未登录，创建临时对话
      if (!isLoggedIn.value) {
        // 创建临时消息
        const userMessage = {
          id: Date.now(),
          role: 'user',
          content: content,
          timestamp: new Date().toISOString()
        }
        
        const aiMessage = {
          id: Date.now() + 1,
          role: 'assistant',
          content: '您好！我是心理咨询机器人，很高兴为您提供帮助。请注意，未登录状态下的对话不会被保存。如需保存对话记录，请先登录。\n\n请告诉我您遇到的问题，我会尽力为您提供专业的心理咨询建议。',
          timestamp: new Date().toISOString()
        }
        
        currentMessages.value.push(userMessage, aiMessage)
        return
      }
      
      if (!currentConversationId.value) {
        await createNewConversation()
      }
      
      try {
        isLoading.value = true
        
        // 添加用户消息到界面
        const userMessage = {
          id: Date.now(),
          role: 'user',
          content: content,
          timestamp: new Date().toISOString()
        }
        currentMessages.value.push(userMessage)
        
        // 准备AI消息容器和状态消息容器
        let aiMessage = null
        let statusMessage = null
        let thinkingMessage = null
        
        // 确定conversation_id（如果是临时ID则传null让后端创建新对话）
        const conversationId = currentConversationId.value?.startsWith('temp_') ? null : currentConversationId.value
        
        // 🔥 流式消息变量
        let currentMsg = null
        
        // 🔥 处理 ReAct 流式数据，根据 type 分类
        function handleEvent(data) {
          console.log('🎯 [ReAct] 处理事件:', data.type, data)

          switch (data.type) {
            case 'start':
              // AI开始思考 - 不再创建单独的状态消息，内容会在思考过程中显示
              console.log('🧠 [ReAct] AI开始思考...')
              break

            case 'user_message':
              // 用户消息确认（通常已经显示了，这里可以忽略）
              break

            case 'react_start':
              // ReAct推理开始 - 不再创建单独的状态消息
              console.log('🔄 [ReAct] 启动ReAct推理架构...')
              break

            case 'iteration_start':
              // 推理循环开始 - 不再创建单独的状态消息，会在思考过程中显示
              console.log(`🔄 [ReAct] 开始第 ${data.iteration} 次推理循环`)
              break

            case 'thinking_chunk':
              // 思考过程片段
              console.log('🎯 [ReAct] 收到思考片段:', data)
              handleThinkingChunk(data)
              break

            case 'action_plan':
              // 行动计划 - 添加思考步骤
              addThinkingStep('正在分析和规划...', true, false)
              break

            case 'observation':
              // 观察阶段 - 标准ReAct的观察步骤
              console.log('👁️ [ReAct] 收到观察结果:', data)
              handleObservation(data)
              break

            case 'action_result':
              // 行动结果 - 添加思考步骤（保留兼容性）
              addThinkingStep('分析完成，正在生成回复...', true, false)
              break

            case 'final_answer_start':
              // 最终答案开始生成
              console.log('💬 [最终答案] 开始生成:', data)
              addThinkingStep('💬 正在生成最终回答...', true, false)
              break

            case 'content':
              // 最终答案内容（流式）
              console.log('💬 [最终答案] 内容片段:', data, '内容:', data.content, '长度:', data.content?.length)
              appendContent(data.content) // 流式显示
              break

            case 'final_answer_complete':
              // 最终答案生成完成
              console.log('💬 [最终答案] 生成完成:', data)
              addThinkingStep('✅ 最终回答生成完成', true, false)
              break

            case 'complete':
              // 处理完成
              console.log('✅ [ReAct] 处理完成:', data)

              // 标记思考完成
              if (thinkingMsg) {
                isCurrentlyThinking.value = false
                addThinkingStep('思考完成', false, true)

                // 更新思考消息状态
                thinkingMsg.isThinking = isCurrentlyThinking
              }

              // 如果有message_id，更新当前AI消息的message_id字段
              if (data.message_id && currentMsg) {
                console.log('🆔 [Complete] 更新消息ID:', data.message_id)
                currentMsg.message_id = data.message_id
              }

              if (data.conversation_id && data.conversation_id !== conversationId) {
                // 更新对话ID
                currentConversationId.value = data.conversation_id
              }

              // 重置流式消息变量
              currentMsg = null
              currentMessageContent = null
              break

            case 'error':
              // 错误处理 - 只记录日志，不创建状态消息
              console.error('❌ [ReAct] 错误:', data.message || data.content)
              break

            default:
              // 其他类型消息 - 只记录日志
              console.log('📝 [ReAct] 其他消息:', data.type, data.message || data.content)
          }

          // 🚀 高性能滚动
          requestAnimationFrame(() => {
            const chatContainer = document.querySelector('.chat-messages')
            if (chatContainer) {
              chatContainer.scrollTop = chatContainer.scrollHeight
            }
          })
        }

        // 🧠 处理思考过程片段 - 累积显示版本
        let thinkingMsg = null
        let allThinkingContent = '' // 累积所有思考内容
        let thinkingIterations = [] // 存储所有迭代的思考过程

        function handleObservation(data) {
          console.log('👁️ [观察] 处理观察结果:', data)

          // 添加观察步骤到思考过程
          const actionName = data.action || '工具'
          const observationText = data.observation || '执行完成'

          // 截断过长的观察结果
          const truncatedObservation = observationText.length > 100
            ? observationText.substring(0, 100) + '...'
            : observationText

          addThinkingStep(`👁️ 观察 ${data.iteration}: ${actionName} - ${truncatedObservation}`, true, true)

          // 如果有详细的观察内容，添加到详细内容中
          if (data.observation && data.observation.length > 100) {
            const detailedObservation = `\n=== 第${data.iteration}次观察详情 ===\n工具: ${actionName}\n结果: ${data.observation}\n`
            currentThinkingContent.value += detailedObservation
            allThinkingContent += detailedObservation

            // 更新思考消息的详细内容
            if (thinkingMsg) {
              thinkingMsg.detailedContent = currentThinkingContent
              thinkingMsg.allThinkingContent.value = String(allThinkingContent || '') // 确保是字符串
            }
          }
        }

        function handleThinkingChunk(data) {
          console.log('🧠 [思考] 处理思考片段:', data)

          // 第一次思考时创建思考消息
          if (!thinkingMsg) {
            isCurrentlyThinking.value = true
            currentThinkingSteps.value = []
            currentThinkingContent.value = ''
            allThinkingContent = '' // 重置累积内容
            thinkingIterations = [] // 重置迭代记录

            thinkingMsg = {
              id: Date.now() + Math.random(),
              role: 'system',
              content: '',
              displayText: '',
              timestamp: new Date().toISOString(),
              type: 'thinking_block',
              iteration: data.iteration,
              thinkingSteps: currentThinkingSteps,
              detailedContent: currentThinkingContent,
              allThinkingContent: ref(''), // 累积的所有思考内容
              thinkingIterations: ref([]), // 所有迭代记录
              isThinking: isCurrentlyThinking
            }
            currentMessages.value.push(thinkingMsg)

            // 添加初始思考步骤
            addThinkingStep('🧠 AI开始思考...', true, false)
          }

          // 检测新的迭代循环
          if (data.iteration && data.iteration !== thinkingMsg.iteration) {
            // 保存上一个迭代的内容
            if (currentThinkingContent.value) {
              thinkingIterations.push({
                iteration: thinkingMsg.iteration,
                content: String(currentThinkingContent.value || ''),
                timestamp: new Date().toISOString()
              })

              // 累积到总内容中
              allThinkingContent += `\n\n=== 第${thinkingMsg.iteration}次思考 ===\n${String(currentThinkingContent.value || '')}`
            }

            // 开始新的迭代
            thinkingMsg.iteration = data.iteration
            addThinkingStep(`🔄 开始第${data.iteration}次推理循环...`, true, false)
          }

          // 累积当前迭代的思考内容
          if (data.full_content_so_far) {
            currentThinkingContent.value = String(data.full_content_so_far || '')
          } else if (data.content) {
            currentThinkingContent.value += String(data.content || '')
          }

          // 更新累积的所有思考内容
          const currentIterationContent = `\n\n=== 第${thinkingMsg.iteration || 1}次思考 ===\n${String(currentThinkingContent.value || '')}`
          const previousIterationsContent = thinkingIterations.map(iter =>
            `\n\n=== 第${iter.iteration}次思考 ===\n${String(iter.content || '')}`
          ).join('')

          allThinkingContent = String(previousIterationsContent + currentIterationContent)

          // 更新思考消息的引用
          if (thinkingMsg) {
            thinkingMsg.detailedContent = currentThinkingContent
            thinkingMsg.allThinkingContent.value = String(allThinkingContent || '') // 确保是字符串
            thinkingMsg.thinkingIterations.value = [...thinkingIterations]
            thinkingMsg.thinkingSteps = currentThinkingSteps
            thinkingMsg.isThinking = isCurrentlyThinking
          }
        }

        // 添加思考步骤
        function addThinkingStep(content, isActive = false, isCompleted = false) {
          // 将之前的活动步骤标记为完成
          currentThinkingSteps.value.forEach(step => {
            if (step.isActive) {
              step.isActive = false
              step.isCompleted = true
            }
          })

          // 检查是否已存在相同内容的步骤
          const existingStep = currentThinkingSteps.value.find(step => step.content === content)
          if (existingStep) {
            existingStep.isActive = isActive
            existingStep.isCompleted = isCompleted
            return
          }

          // 添加新步骤
          currentThinkingSteps.value.push({
            id: Date.now() + Math.random(),
            content,
            isActive,
            isCompleted,
            timestamp: new Date().toISOString()
          })
        }

        // 🔥 使用响应式变量实现真正的流式显示（参考思考过程的成功模式）
        let currentMessageContent = null // 响应式变量引用

        function appendContent(text) {
          console.log('🔥 [appendContent] 被调用，文本:', text, '长度:', text?.length)

          // 第一次 content 时新建消息
          if (!currentMsg) {
            console.log('🔥 [appendContent] 创建新消息')

            // 创建响应式变量（像思考过程一样）
            currentMessageContent = ref('')

            currentMsg = {
              id: Date.now() + 3,
              role: 'assistant',
              content: currentMessageContent, // 使用响应式变量引用
              displayText: currentMessageContent, // 使用响应式变量引用
              timestamp: new Date().toISOString(),
              type: 'content'
            }
            currentMessages.value.push(currentMsg)
            console.log('🔥 [appendContent] 新消息已添加到列表，当前消息数:', currentMessages.value.length)
          }

          // 更新响应式变量（像思考过程一样）
          const oldContent = currentMessageContent.value
          currentMessageContent.value += text

          console.log('🔥 [appendContent] 响应式内容更新:', {
            '添加的文本': text,
            '之前长度': oldContent.length,
            '现在长度': currentMessageContent.value.length
          })

          // Vue的响应式系统会自动检测到变化并更新UI
        }
        
        // 调用流式聊天API
         const response = await api.streamChat(content, conversationId, userInfo.value?.user_id)
         
         // 处理流式响应 - 修复数据分割问题
         const reader = response.body.getReader()
         const decoder = new TextDecoder('utf-8')
         let buffer = ''
         
         while (true) {
           const { done, value } = await reader.read()
           if (done) break
           
           buffer += decoder.decode(value, { stream: true })
           
           // 🔥 修复：按行分割，然后处理每个data:行
           const lines = buffer.split('\n')
           buffer = lines.pop() || '' // 保留最后一行（可能不完整）
           
           for (const line of lines) {
             const trimmedLine = line.trim()
             if (!trimmedLine.startsWith('data: ')) continue
             
             const raw = trimmedLine.slice(6).trim()
             if (raw === '[DONE]') {
               isLoading.value = false
               // 重置流式消息变量
               currentMsg = null
               return
             }
             
             if (raw) { // 确保不是空字符串
               try {
                 const data = JSON.parse(raw)
                 handleEvent(data) // 处理不同类型消息

                 // 检查是否完成
                 if (data.type === 'complete') {
                   isLoading.value = false

                   // 确保最终消息显示完整内容（已经在appendContent中同步了）
                   if (currentMsg && currentMsg.content) {
                     currentMsg.displayText = currentMsg.content
                   }

                   // 清理引用但不删除消息
                   currentMsg = null
                   thinkingMsg = null
                   // 清理思考状态
                   isCurrentlyThinking.value = false

                   // 更新对话ID（如果有新的对话ID）
                   if (data.conversation_id && data.conversation_id !== currentConversationId.value) {
                     currentConversationId.value = data.conversation_id
                   }

                   // 重新加载对话列表但不重新加载当前消息（避免清空思考内容）
                   if (isLoggedIn.value) {
                     try {
                       const response = await api.getConversations()
                       if (response.success) {
                         // 按时间倒序排列（最新的在上面）
                         const sortedConversations = response.data.sort((a, b) => {
                           const dateA = new Date(a.created_at || a.updated_at)
                           const dateB = new Date(b.created_at || b.updated_at)
                           return dateB - dateA // 倒序排列
                         })
                         conversations.value = sortedConversations
                         // 不调用 loadMessages，保持当前消息显示
                       }
                     } catch (error) {
                       console.error('加载对话列表失败:', error)
                     }
                   }
                   return
                 }
               } catch (err) {
                 console.error('JSON 解析失败:', err, '原始数据:', raw)
               }
             }
           }
         }
      } catch (error) {
        console.error('发送消息失败:', error)
      } finally {
        isLoading.value = false
      }
    }

    // 清空当前聊天（仅清空界面显示，不删除服务器记录）
    const clearCurrentChat = () => {
      currentMessages.value = []
    }

    // 导出当前聊天
    const exportCurrentChat = () => {
      if (currentMessages.value.length === 0) return
      
      const content = currentMessages.value
        .map(msg => `${msg.role === 'user' ? '用户' : 'AI'}: ${msg.content}`)
        .join('\n\n')
      
      const blob = new Blob([content], { type: 'text/plain' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `chat-${new Date().toISOString().slice(0, 10)}.txt`
      a.click()
      URL.revokeObjectURL(url)
    }

    // 切换侧边栏折叠状态
    const toggleSidebar = () => {
      sidebarCollapsed.value = !sidebarCollapsed.value
    }

    // 获取当前对话标题
    const getCurrentConversationTitle = () => {
      if (!currentConversationId.value) {
        return '心理健康助手'
      }
      
      const currentConversation = conversations.value.find(
        conv => conv.conversation_id === currentConversationId.value
      )
      
      return currentConversation?.title || '心理健康助手'
    }

    // 处理消息反馈更新
    const handleFeedbackUpdated = async (messageId, feedback) => {
      console.log('处理反馈更新:', messageId, feedback)
      // 重新加载当前对话的消息以获取最新的反馈状态
      if (currentConversationId.value && !currentConversationId.value.startsWith('temp_')) {
        await loadMessages(currentConversationId.value)
      }
    }

    // 处理对话标题更新
    const handleTitleUpdated = async (event) => {
      console.log('🔄 处理标题更新事件:', event)
      try {
        // 重新加载对话列表以获取最新的标题
        await loadConversations()
        console.log('✅ 对话列表已刷新')
      } catch (error) {
        console.error('❌ 刷新对话列表失败:', error)
      }
    }



    // 🔥 Vue3最佳实践：滚动逻辑已移至ChatArea.vue的watch中，无需在此处理

    // 组件挂载时初始化
    onMounted(() => {
      // 初始化主题
      themeStore.initTheme()
      // 检查登录状态
      checkLoginStatus()
    })

    // 🎯 用户引导相关方法
    const handleGuideCompleted = () => {
      console.log('✅ [App] 用户引导完成')
      // 显示快速开始建议
      if (quickStartRef.value) {
        setTimeout(() => {
          quickStartRef.value.showSuggestionsPanel()
        }, 500)
      }
    }

    const handleGuideSkipped = () => {
      console.log('⏭️ [App] 用户跳过引导')
      // 可以显示简化的快速开始建议
      if (quickStartRef.value) {
        setTimeout(() => {
          quickStartRef.value.showSuggestionsPanel()
        }, 300)
      }
    }

    const handleSuggestionSelected = (suggestion) => {
      console.log('🎯 [App] 用户选择建议:', suggestion.title)
      // 自动发送建议的提示消息
      if (suggestion.prompt) {
        sendMessage(suggestion.prompt)
      }
    }

    const handleDirectChatStarted = () => {
      console.log('💬 [App] 用户选择直接对话')
      // 可以发送欢迎消息或者直接开始
    }

    const handleSuggestionsHidden = () => {
      console.log('👋 [App] 快速开始建议已隐藏')
    }

    return {
      // Pinia 状态
      isLoggedIn,
      userInfo,
      themeStore,
      // 本地状态
      conversations,
      currentConversationId,
      currentMessages,
      isLoading,
      showProfile,
      showSettings,
      showLogin,
      showMobileSidebar,
      sidebarCollapsed,
      chatAreaRef, // ChatArea组件引用
      userGuideRef, // 用户引导组件引用
      quickStartRef, // 快速开始建议组件引用
      // 思考过程相关
      currentThinkingSteps,
      currentThinkingContent,
      isCurrentlyThinking,
      handleLoginSuccess,
      handleLogout,
      createNewConversation,
      selectConversation,
      deleteConversation,
      sendMessage,
      clearCurrentChat,
      exportCurrentChat,
      toggleSidebar,
      getCurrentConversationTitle,
      handleFeedbackUpdated,
      handleTitleUpdated,
      // 用户引导相关方法
      handleGuideCompleted,
      handleGuideSkipped,
      handleSuggestionSelected,
      handleDirectChatStarted,
      handleSuggestionsHidden
    }
  }
}
</script>

<style scoped>
.auth-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.auth-container h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.auth-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
}

.auth-tabs .btn {
  flex: 1;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info span {
  color: #666;
}
</style>